<?php
// +---------------------------------------------------------------------+
// | OneBase    | [ WE CAN DO IT JUST THINK ]                            |
// +---------------------------------------------------------------------+
// | Licensed   | http://www.apache.org/licenses/LICENSE-2.0 )           |
// +---------------------------------------------------------------------+
// | Author     | 王勇程 <laughskydragon@qq.com>                         |
// +---------------------------------------------------------------------+
// | Repository | https://gitee.com/Bigotry/OneBase                      |
// +---------------------------------------------------------------------+

namespace app\common\logic;

/**
 * 商品分类业务逻辑
 */
class Category extends LogicBase
{
    /**
     * 获取分类列表搜索条件
     */
    public function getWhere($data = [])
    {
        $where = [];
        
        // 父分类ID
        if (isset($data['parent_id'])) {
            $where['parent_id'] = $data['parent_id'];
        }
        
        // 状态筛选
        if (!empty($data['status'])) {
            $where['status'] = $data['status'];
        } else {
            $where['status'] = ['<>', -1]; // 排除已删除
        }
        
        // 关键词搜索
        if (!empty($data['search_data'])) {
            $where['name'] = ['like', '%' . $data['search_data'] . '%'];
        }
        
        return $where;
    }
    
    /**
     * 获取分类列表
     */
    public function getCategoryList($where = [])
    {
        // 处理搜索条件
        $searchWhere = $this->getWhere($where);
        
        // 如果有搜索条件，返回扁平列表
        if (!empty($where['search_data']) || !empty($where['name'])) {
            $list = $this->modelCategory->getList($searchWhere, true, 'sort asc, id asc', false);
            
            if ($list) {
                foreach ($list as $key => $item) {
                    // 获取子分类数量
                    $item['children_count'] = $this->modelCategory->stat(['parent_id' => $item['id'], 'status' => ['<>', -1]], 'count');
                    // 判断是否可以删除
                    $item['can_delete'] = $item['children_count'] == 0;
                    // 添加层级信息
                    $item['level'] = $this->getCategoryLevel($item['id']);
                    $item['prefix'] = $item['level'] > 0 ? str_repeat('├─', $item['level']) : '';
                    
                    // 重新赋值修改后的数据
                    $list[$key] = $item;
                }
            }
            
            return [RESULT_SUCCESS, '获取成功', ['data' => $list ?: [], 'total' => count($list ?: [])]];
        }
        
        // 无搜索条件时，构建树状结构
        $allCategories = $this->modelCategory->getList($searchWhere, true, 'sort asc, id asc', false);
        
        if (!$allCategories) {
            return ['data' => [], 'total' => 0];
        }
        
        // 为每个分类添加额外信息
        foreach ($allCategories as $key => $item) {
            // 获取子分类数量
            $item['children_count'] = $this->modelCategory->stat(['parent_id' => $item['id'], 'status' => ['<>', -1]], 'count');
            // 判断是否可以删除
            $item['can_delete'] = $item['children_count'] == 0;
            
            // 重新赋值修改后的数据
            $allCategories[$key] = $item;
        }
        
        // 构建树状结构
        $treeList = $this->buildCategoryTreeForList($allCategories, 0, 0);
        
        return [RESULT_SUCCESS, '获取成功', ['data' => $treeList, 'total' => count($treeList)]];
    }
    
    /**
     * 获取分类详情
     */
    public function getCategoryInfo($where = [], $field = true)
    {
        $info = $this->modelCategory->getInfo($where, $field);
        
        if (!$info) {
            return [RESULT_ERROR, '分类不存在'];
        }
        
        return [RESULT_SUCCESS, '获取成功', $info];
    }
    
    /**
     * 分类编辑
     */
    public function categoryEdit($data = [])
    {
        $validate_result = $this->validateCategory->scene('edit')->check($data);
        
        if (!$validate_result) {
            
            return [RESULT_ERROR, $this->validateCategory->getError()];
        }
        
        $url = url('categoryList');
        
        $isUpdate = !empty($data['id']);
        $oldParentId = null;
        
        // 如果是更新操作，获取原来的parent_id
        if ($isUpdate) {
            $oldCategory = $this->modelCategory->getInfo(['id' => $data['id']], 'parent_id');
            $oldParentId = $oldCategory['parent_id'] ?? 0;
        }
        
        $result = $this->modelCategory->setInfo($data);
        
        // 如果操作成功，更新分类路径
        if ($result) {
            $categoryId = $isUpdate ? $data['id'] : $result;
            $newParentId = $data['parent_id'] ?? 0;
            
            // 更新当前分类的路径和层级
            $this->modelCategory->updateCategoryPath($categoryId, $newParentId);
            
            // 如果是更新操作且父分类发生了变化，需要更新所有子分类
            if ($isUpdate && $oldParentId != $newParentId) {
                $this->modelCategory->updateChildrenPath($categoryId);
            }
        }
        
        $handle_text = empty($data['id']) ? '新增' : '编辑';
        
        $result && action_log($handle_text, '分类' . $handle_text . '，name：' . $data['name']);
        
        return $result ? [RESULT_SUCCESS, '操作成功', $url] : [RESULT_ERROR, $this->modelCategory->getError()];
    }
    
    /**
     * 分类删除
     */
    public function categoryDel($where = [])
    {
        $result = $this->modelCategory->deleteInfo($where);
        
        $result && action_log('删除', '分类删除，where：' . http_build_query($where));
        
        return $result ? [RESULT_SUCCESS, '分类删除成功'] : [RESULT_ERROR, $this->modelCategory->getError()];
    }
    
    /**
     * 获取分类选择器数据
     */
    public function getCategorySelector($data = [])
    {
        $excludeId = $data['exclude_id'] ?? 0;
        $selectedId = $data['selected_id'] ?? 0;
        
        // 获取所有有效分类
        $where = ['status' => ['<>', -1]];
        
        // 排除指定分类及其子分类
        if ($excludeId) {
            $excludeIds = [$excludeId];
            // 获取所有子分类ID
            $children = $this->getChildrenIds($excludeId);
            $excludeIds = array_merge($excludeIds, $children);
            $where['id'] = ['not in', $excludeIds];
        }
        
        $list = $this->modelCategory->getList($where, 'id,name,parent_id', 'sort asc, id asc', false);
        
        if (!$list) {
            return false;
        }
        
        // 构建树形结构
        $tree = $this->buildCategoryTree($list, 0, $selectedId);
        
        return $tree;
    }
    
    /**
     * 分类状态编辑
     */
    public function editCategory($data = [])
    {
        $categoryId = $data['id'] ?? 0;
        $status = $data['status'] ?? 1;
        
        if (!$categoryId) {
            return [RESULT_ERROR, '分类ID不能为空'];
        }
        
        // 检查分类是否存在
        $category = $this->modelCategory->getInfo(['id' => $categoryId]);
        if (!$category) {
            return [RESULT_ERROR, '分类不存在'];
        }
        
        $result = $this->modelCategory->updateInfo(['id' => $categoryId], ['status' => $status]);
        
        $statusText = $status == 1 ? '启用' : '禁用';
        $result && action_log('状态切换', '分类状态切换，ID：' . $categoryId . '，状态：' . $statusText);
        
        return $result ? [RESULT_SUCCESS, '状态切换成功'] : [RESULT_ERROR, $this->modelCategory->getError()];
    }
    
    /**
     * 批量操作
     */
    public function batchCategory($data = [])
    {
        $ids = $data['ids'] ?? [];
        $action = $data['action'] ?? '';
        
        if (empty($ids)) {
            return [RESULT_ERROR, '请选择要操作的分类'];
        }
        
        if (!is_array($ids)) {
            $ids = explode(',', $ids);
        }
        
        $ids = array_filter(array_map('intval', $ids));
        
        if (empty($ids)) {
            return [RESULT_ERROR, '分类ID格式错误'];
        }
        
        switch ($action) {
            case 'delete':
                return $this->batchDelete($ids);
            case 'enable':
                return $this->batchUpdateStatus($ids, 1);
            case 'disable':
                return $this->batchUpdateStatus($ids, 0);
            default:
                return [RESULT_ERROR, '不支持的操作类型'];
        }
    }
    
    /**
     * 更新分类排序
     */
    public function updateCategorySort($data = [])
    {
        $sorts = $data['sorts'] ?? [];
        
        if (empty($sorts)) {
            return [RESULT_ERROR, '排序数据不能为空'];
        }
        
        try {
            \think\facade\Db::transaction(function () use ($sorts) {
                foreach ($sorts as $item) {
                    $id = $item['id'] ?? 0;
                    $sort = $item['sort'] ?? 0;
                    
                    if ($id > 0) {
                        $this->modelCategory->updateInfo(['id' => $id], ['sort' => $sort]);
                    }
                }
            });
            
            action_log('排序', '分类排序更新，数量：' . count($sorts));
            
            return [RESULT_SUCCESS, '排序更新成功'];
            
        } catch (\Exception $e) {
            \think\facade\Log::error('分类排序更新失败：' . $e->getMessage());
            return [RESULT_ERROR, '排序更新失败'];
        }
    }
    
    /**
     * 获取子分类ID列表（递归）
     */
    private function getChildrenIds($parentId)
    {
        $children = [];
        $list = $this->modelCategory->getList(['parent_id' => $parentId], 'id', '', false);
        
        if ($list) {
            foreach ($list as $item) {
                $children[] = $item['id'];
                // 递归获取子分类的子分类
                $subChildren = $this->getChildrenIds($item['id']);
                $children = array_merge($children, $subChildren);
            }
        }
        
        return $children;
    }
    
    /**
     * 构建分类树形结构（用于选择器）
     */
    private function buildCategoryTree($list, $parentId = 0, $selectedId = 0, $level = 0)
    {
        $tree = [];
        
        foreach ($list as $item) {
            if ($item['parent_id'] == $parentId) {
                $item['level'] = $level;
                $item['selected'] = ($item['id'] == $selectedId);
                $item['prefix'] = str_repeat('　', $level);
                // 添加带层级的名称
                $item['name_with_level'] = $item['prefix'] . $item['name'];
                
                $tree[] = $item;
                
                // 递归获取子分类
                $children = $this->buildCategoryTree($list, $item['id'], $selectedId, $level + 1);
                $tree = array_merge($tree, $children);
            }
        }
        
        return $tree;
    }
     
     /**
      * 构建分类树形结构（用于列表显示）
      */
     private function buildCategoryTreeForList($list, $parentId = 0, $level = 0)
     {
         $tree = [];
         
         foreach ($list as $item) {
             if ($item['parent_id'] == $parentId) {
                 $item['level'] = $level;
                 $item['prefix'] = $level > 0 ? str_repeat('├─', $level) : '';
                 
                 $tree[] = $item;
                 
                 // 递归获取子分类
                 $children = $this->buildCategoryTreeForList($list, $item['id'], $level + 1);
                 $tree = array_merge($tree, $children);
             }
         }
         
         return $tree;
     }
     
     /**
      * 获取分类层级
      */
     private function getCategoryLevel($categoryId, $level = 0)
     {
         $category = $this->modelCategory->getInfo(['id' => $categoryId], 'parent_id');
         
         if (!$category || $category['parent_id'] == 0) {
             return $level;
         }
         
         return $this->getCategoryLevel($category['parent_id'], $level + 1);
     }
    
    /**
     * 批量删除分类
     */
    private function batchDelete($ids)
    {
        try {
            \think\facade\Db::transaction(function () use ($ids) {
                foreach ($ids as $id) {
                    // 检查是否有子分类
                    $childCount = $this->modelCategory->stat(['parent_id' => $id, 'status' => ['<>', -1]], 'count');
                    if ($childCount > 0) {
                        throw new \Exception('分类ID ' . $id . ' 下还有子分类，无法删除');
                    }
                    
                    $this->modelCategory->deleteInfo(['id' => $id]);
                }
            });
            
            action_log('批量删除', '批量删除分类，ID：' . implode(',', $ids));
            
            return [RESULT_SUCCESS, '批量删除成功'];
            
        } catch (\Exception $e) {
            return [RESULT_ERROR, $e->getMessage()];
        }
    }
    
    /**
     * 批量更新状态
     */
    private function batchUpdateStatus($ids, $status)
    {
        try {
            \think\facade\Db::transaction(function () use ($ids, $status) {
                foreach ($ids as $id) {
                    $this->modelCategory->updateInfo(['id' => $id], ['status' => $status]);
                }
            });
            
            $statusText = $status == 1 ? '启用' : '禁用';
            action_log('批量状态切换', '批量' . $statusText . '分类，ID：' . implode(',', $ids));
            
            return [RESULT_SUCCESS, '批量' . $statusText . '成功'];
            
        } catch (\Exception $e) {
            return [RESULT_ERROR, '批量操作失败：' . $e->getMessage()];
        }
    }

    /**
     * 获取分类选项（用于产品编辑页面）
     */
    public function getCategoryOptions($data = [])
    {
        try {
            // 获取所有有效分类 - 使用ModelBase封装方法
            $where = ['status' => 1];
            $list = $this->modelCategory->getList($where, 'id,name,parent_id', 'sort asc, id asc', false);
            
            if (!$list) {
                return false;
            }
            
            // 构建树形结构
            $tree = $this->buildCategoryTreeForOptions($list, 0);
            
            return $tree;
            
        } catch (\Exception $e) {
            \think\facade\Log::error('获取分类选项失败：' . $e->getMessage());
            return false;
        }
    }

    /**
     * 构建分类树形结构（用于选项）
     */
    private function buildCategoryTreeForOptions($list, $parentId = 0, $level = 0)
    {
        $tree = [];
        
        foreach ($list as $item) {
            if ($item['parent_id'] == $parentId) {
                $item['level'] = $level;
                $item['children'] = $this->buildCategoryTreeForOptions($list, $item['id'], $level + 1);
                $tree[] = $item;
            }
        }
        
        return $tree;
    }

}